<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>借阅管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增借阅
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="searchForm" :inline="true">
          <el-form-item label="图书名称">
            <el-input v-model="searchForm.bookTitle" placeholder="请输入图书名称" clearable />
          </el-form-item>
          <el-form-item label="借阅人">
            <el-input v-model="searchForm.borrowerName" placeholder="请输入借阅人姓名" clearable />
          </el-form-item>
          <el-form-item label="借阅状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="借阅中" value="BORROWED" />
              <el-option label="已归还" value="RETURNED" />
              <el-option label="逾期" value="OVERDUE" />
              <el-option label="丢失" value="LOST" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="bookTitle" label="图书名称" width="200" />
        <el-table-column prop="bookAuthor" label="作者" width="120" />
        <el-table-column prop="borrowerName" label="借阅人" width="120" />
        <el-table-column prop="borrowerPhone" label="联系电话" width="120" />
        <el-table-column prop="borrowDate" label="借阅日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="应还日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.dueDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="实际归还日期" width="120">
          <template #default="scope">
            {{ scope.row.returnDate ? formatDate(scope.row.returnDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fine" label="罚金" width="80">
          <template #default="scope">
            {{ scope.row.fine ? `¥${scope.row.fine}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'BORROWED'" 
              type="success" 
              size="small" 
              @click="handleReturn(scope.row)"
            >
              归还
            </el-button>
            <el-button 
              v-if="scope.row.status === 'BORROWED'" 
              type="warning" 
              size="small" 
              @click="handleRenew(scope.row)"
            >
              续借
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="图书" prop="bookId">
          <el-select v-model="form.bookId" placeholder="请选择图书" filterable>
            <el-option
              v-for="book in books"
              :key="book.id"
              :label="`${book.title} - ${book.author}`"
              :value="book.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="借阅人" prop="borrowerName">
          <el-input v-model="form.borrowerName" placeholder="请输入借阅人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="borrowerPhone">
          <el-input v-model="form.borrowerPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="借阅日期" prop="borrowDate">
          <el-date-picker
            v-model="form.borrowDate"
            type="date"
            placeholder="请选择借阅日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="应还日期" prop="dueDate">
          <el-date-picker
            v-model="form.dueDate"
            type="date"
            placeholder="请选择应还日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  bookTitle: '',
  borrowerName: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const books = ref([])

// 表单数据
const form = reactive({
  id: undefined,
  bookId: '',
  borrowerName: '',
  borrowerPhone: '',
  borrowDate: null,
  dueDate: null,
  remark: ''
})

// 表单验证规则
const rules = reactive({
  bookId: [{ required: true, message: '请选择图书', trigger: 'change' }],
  borrowerName: [{ required: true, message: '请输入借阅人姓名', trigger: 'blur' }],
  borrowerPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  borrowDate: [{ required: true, message: '请选择借阅日期', trigger: 'change' }],
  dueDate: [{ required: true, message: '请选择应还日期', trigger: 'change' }]
})

// 计算属性
const dialogTitle = computed(() => {
  return form.id ? '编辑借阅记录' : '新增借阅记录'
})

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    const mockData = {
      records: [
        {
          id: 1,
          bookTitle: 'JavaScript高级程序设计',
          bookAuthor: 'Nicholas C. Zakas',
          borrowerName: '张三',
          borrowerPhone: '13800138001',
          borrowDate: '2024-01-15',
          dueDate: '2024-02-15',
          returnDate: null,
          status: 'BORROWED',
          fine: 0
        },
        {
          id: 2,
          bookTitle: 'Vue.js设计与实现',
          bookAuthor: '霍春阳',
          borrowerName: '李四',
          borrowerPhone: '13800138002',
          borrowDate: '2024-01-10',
          dueDate: '2024-02-10',
          returnDate: '2024-02-08',
          status: 'RETURNED',
          fine: 0
        }
      ],
      total: 2
    }
    
    tableData.value = mockData.records
    pagination.total = mockData.total
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
  } finally {
    loading.value = false
  }
}

// 获取图书列表
const getBooks = async () => {
  try {
    // 模拟API调用
    books.value = [
      { id: 1, title: 'JavaScript高级程序设计', author: 'Nicholas C. Zakas' },
      { id: 2, title: 'Vue.js设计与实现', author: '霍春阳' },
      { id: 3, title: 'React技术揭秘', author: '卡颂' }
    ]
  } catch (error) {
    console.error('获取图书列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    bookTitle: '',
    borrowerName: '',
    status: ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条借阅记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 归还
const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要归还这本图书吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    ElMessage.success('归还成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('归还失败')
    }
  }
}

// 续借
const handleRenew = async (row) => {
  try {
    await ElMessageBox.confirm('确定要续借这本图书吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    ElMessage.success('续借成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('续借失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(form.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    bookId: '',
    borrowerName: '',
    borrowerPhone: '',
    borrowDate: null,
    dueDate: null,
    remark: ''
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
  formRef.value?.clearValidate()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  getList()
}

// 工具函数
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

const getStatusText = (status) => {
  const statusMap = {
    'BORROWED': '借阅中',
    'RETURNED': '已归还',
    'OVERDUE': '逾期',
    'LOST': '丢失'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    'BORROWED': 'primary',
    'RETURNED': 'success',
    'OVERDUE': 'danger',
    'LOST': 'warning'
  }
  return typeMap[status] || 'info'
}

// 页面加载
onMounted(() => {
  getList()
  getBooks()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>
